<?php
/* SECURITY (don't touch) */
defined('_INCL')||(header('HTTP/1.1 403 Forbidden')&die('403.14 - Access denied.'));
/**************************/
?>

<div class="FakeForm">
<?
switch ($_REQUEST['Action']){
	
	case 'Delete':
		if( $_REQUEST['Input'] === 'Jeg ved hvad jeg laver'){
			echo '<h1>Du ved hvad du laver</h1><hr/>';
			//echo '<pre>'; print_r($_REQUEST); echo '</pre>';//DEBUG
			
			if( deleteFiles($_REQUEST['File']) ){
				echo	"<h3>Du har slettet:</h3>".
						"<p>$_REQUEST[File]</p>";
			} else {
				echo	"<h3>Noget gik galt i sletningen af:</h3>".
						"<p>$_REQUEST[File]</p>";		
			}
		} else {
			echo '<h1>Du ved IKKE hvad du laver</h1><hr/>';
			//echo '<pre>'; print_r($_REQUEST); echo '</pre>';//DEBUG
			echo	"<h3>Sletningen blev annuleret af:</h3>".
					"<p>$_REQUEST[File]</p>";
		}
		echo '<hr/><p><a href="QRcreate.main.php" class="Button">OK</a></p>';
		break 1;
		
		
	case 'Make':
		//SANITIZE USER-INPUT
		$_REQUEST['ProdSerie'] = (empty($_REQUEST['ProdSerieNew'])) ? $_REQUEST['ProdSerieOld'] : $_REQUEST['ProdSerieNew'];
		unset($_REQUEST['ProdSerieNew'],$_REQUEST['ProdSerieOld']);
		$_REQUEST['ProdSerie'] = (empty($_REQUEST['ProdSerie'])) ? 'XXX' : substr($_REQUEST['ProdSerie'],0,2);
	
		$_REQUEST['NumStart'] = (empty($_REQUEST['NumStart'])) ? 1 : (integer)(substr($_REQUEST['NumStart'],0,6));
		$_REQUEST['NumEnd'] = (empty($_REQUEST['NumEnd'])) ? 51 : (integer)(substr($_REQUEST['NumEnd'],0,6));

		$error = 0;
		if( in_array('XXX',$_REQUEST,true) ){ $error++; echo '<p>Der mangler input.</p>'; }
		if( $_REQUEST['NumStart']+48 >= $_REQUEST['NumEnd'] ){ $error++; echo '<h3>Fejl i numrene.</h3>'; }
	
		//TODO: Check numbers as a continuation of an existing Series!
	
		if($error){
			if(_DEBUG) { echo '<pre>'; print_r($_REQUEST); echo '</pre>'; }
			die('<p>... Dit input er altså helt i skoven :)</p>'.PHP_EOL.'<a href="QRcreate.main.php" class="Button">Tilbage</a></div>');
		}
		
		//PRODUCTION SETUP
		$Search = $WorkDirName.$FilePrefix.$_REQUEST['ProdSerie'].'('.$_REQUEST['NumStart'].'-'.$_REQUEST['NumEnd'].')';
		foreach($ProdSeries['Existing'] as $Alphas => $Unit){//Check if series allready exists
			if( $Alphas !== 'Info' ){
				foreach($Unit as $Zip => $Content){
					if( $Zip !== 'Info' ){
						$Found = explode('|',$Content['Dir']);
						if( $Search === $Found[0] ){
							die('<p>Denne produktionsserie eksisterer allerede! (<a class="Button" href="QRcreate.main.php">Tilbage</a>)</p></div>');
						}
					}
				}
			}
		}		
		
		//PRODUCTION LOOP
		$FolderName = $FilePrefix.$_REQUEST['ProdSerie'].'('.$_REQUEST['NumStart'].'-'.$_REQUEST['NumEnd'].')'.date('|d.M.Y-H.i|');
		$FolderPath = $WorkDir.$FolderName.DIRECTORY_SEPARATOR;
		
		mkdir($FolderPath); file_put_contents($FolderPath.'index.php','Closed Area.',LOCK_EX);
		$Output[0] = "<h3><b>$_REQUEST[ProdSerie]</b>-serien: $_REQUEST[NumStart]-$_REQUEST[NumEnd]</h3><p>... Første, miderste og sidste enhed i denne kørsel</p><hr/>";

		$Middle = floor(($_REQUEST['NumEnd']-$_REQUEST['NumStart'])/2) + $_REQUEST['NumStart'];
		for($n=$_REQUEST['NumStart']; $n<=$_REQUEST['NumEnd']; $n++){
			$CurrentNumber = ZeroPad($n,6);
			$CurrentSecret = makeSecret();
			//TODO: Save Series,Number,Secret in DB for later association with user-accounts		
	
			//Make and save the image
			$CurrentImg = makeImg($CurrentNumber,$CurrentSecret);
			$ImgName = $ImagePrefix.$_REQUEST['ProdSerie'].$CurrentNumber.'_'.$CurrentSecret.'.png';
			imagepng($CurrentImg, $FolderPath.$ImgName, 9, PNG_FILTER_NONE);
			ImageDestroy($CurrentImg);
	
			if( $n == $_REQUEST['NumStart'] || $n == $Middle || $n == $_REQUEST['NumEnd'] ){
				$Output[] = $ImgName;
			}
		}
		
		$FolderPath = '../'.$WorkDirName.zipIt($FolderPath);
		$Output[1] = "\t<img src='$FolderPath/$Output[1]' alt='Eksempel'/>".PHP_EOL;//Show image on page
		$Output[2] = "\t<img src='$FolderPath/$Output[2]' alt='Eksempel'/>".PHP_EOL;//Show image on page
		$Output[3] = "\t<img src='$FolderPath/$Output[3]' alt='Eksempel'/>".PHP_EOL;//Show image on page

		echo	implode('',$Output).'<hr/><p><a href="QRcreate.main.php" class="Button">OK</a></p>';
		break 1;
	
	
	default:
		echo '<pre>'; print_r($_REQUEST); echo '</pre>';//DEBUG
		die('ERROR');
		break 1;
}

Sess_Close();

?>

</div>

</body>
</html>

<?



//----------------------------------------------
function deleteFiles($ZipName){
	global $WorkDir;
	
	$ZipFile = $WorkDir.$ZipName;
	$ImgDir = substr($ZipFile,0,-4).DIRECTORY_SEPARATOR;
	
	if( is_file($ZipFile) || is_dir($ImgDir) ){
		if ($H=opendir($ImgDir)) {
			while( ($Item=readdir($H)) !== false ){
				if(!is_dir($Item)){
					unlink($ImgDir.$Item);
				}
			}
		}
		closedir($H);
		rmdir($ImgDir);
		unlink($ZipFile);
		return true;
	}
	return false;
}


//----------------------------------------------
function makeSecret(){
	global $SeriesGlyphs;
	$Units = $SeriesGlyphs;
	shuffle($Units);
	$Units = array_chunk($Units,8);
	return implode('',$Units[0]);
}


//----------------------------------------------
function makeImg($CurrentNumber,$CurrentSecret,$PrintTxt=true){
	
	$DataEncoded = codeData($_REQUEST['ProdSerie'].$CurrentNumber,$CurrentSecret,'encode');
	
	$PxPerBit = 10;//px in final image
	$FontSize = 5;
	$Bytes = strlen($DataEncoded);
	$BytesPerLine = ceil(sqrt($Bytes));
	$ByteW = 3;//horizontal bits per byte-block (3)
	$ByteH = 2;//vertical bits per byte-block (2)
	
	$ImgW = $BytesPerLine*$ByteW;//px
	$ImgH = $BytesPerLine*$ByteH;//px
	
	//Create CodeImage
	$CodeImage = ImageCreate($ImgW,$ImgH);
		$col[0] = ImageColorAllocate($CodeImage,255,255,255);//BG
		$col[1] = ImageColorAllocate($CodeImage,0,0,0);//Pixel
		imagefill($CodeImage,0,0,$col[0]);
	
	global $GlyphCodings;
	for($i=0; $i<$Bytes; $i++){//Traverse datastring
		$xOffset = ($i%$BytesPerLine)*$ByteW;
		$yOffset = floor($i/$BytesPerLine)*$ByteH;
		$Glyph = substr($DataEncoded,$i,1);
		$GlyphCode = $GlyphCodings[$Glyph];
		for($p=0; $p<strlen($GlyphCode); $p++){
			$x = $p%$ByteW +$xOffset;
			$y = floor($p/$ByteW) +$yOffset;
			$bit = substr($GlyphCode,$p,1);
			ImageSetPixel($CodeImage,$x,$y,$col[$bit]);
		}
	}
	
	//Create EndImage
	$TxtSpace = ($PrintTxt) ? $FontSize*5 : 0;
	$FrameStroke = floor($PxPerBit/2);
	$FrameSpace = $FrameStroke+$PxPerBit;
	$EndW = $FrameSpace+($ImgW*$PxPerBit)+$FrameSpace;
	$EndH = $TxtSpace+($ImgH*$PxPerBit)+$FrameSpace;
	
	$EndImg = ImageCreate($EndW+1,$EndH+1);
	$col[0] = ImageColorAllocate($EndImg,255,255,255);//BG
	$col[1] = ImageColorAllocate($EndImg,0,0,0);//Pixel
	imagefill($EndImg,0,0,$col[1]);
	imagefilledrectangle($EndImg, $FrameStroke,-$FrameStroke, $EndW-$FrameStroke,$EndH-$FrameStroke, $col[0]);
	
	ImageCopyResized($EndImg,$CodeImage, $FrameSpace,$TxtSpace, 0,0, $ImgW*$PxPerBit,$ImgH*$PxPerBit, $ImgW,$ImgH);
	ImageDestroy($CodeImage);
	
	//Write human-readable text in image
	if( $PrintTxt ){
		$PrintString = $_REQUEST['ProdSerie'].' '.substr($CurrentNumber,0,3).' '.substr($CurrentNumber,3).' '.substr($CurrentSecret,0,2);
		$x = $FrameSpace;
		$y = -2;
		imagestring ($EndImg,$FontSize,$x,$y,$PrintString,$col[1]);
		imagestring ($EndImg,$FontSize,$x,$y+1,$PrintString,$col[1]);//Bold-effect on text
	}
	
	return $EndImg;
}


//----------------------------------------------
function zipIt($FolderPath){
	
	$ParentPath = pathinfo($FolderPath,PATHINFO_DIRNAME);
	$FolderName = pathinfo($FolderPath,PATHINFO_BASENAME);
	$ZipPath = $ParentPath.DIRECTORY_SEPARATOR.$FolderName.'.zip';
	// [, int $options = PATHINFO_DIRNAME | PATHINFO_BASENAME | PATHINFO_EXTENSION | PATHINFO_FILENAME ] 
	//echo $FolderPath.'<br/>'.$ParentPath.'<br/>'.$FolderName.'<br/>'.$ZipPath; die();//DEBUG
	
	global $ImagePrefix;
	$zip = new ZipArchive;
	$R = $zip->open($ZipPath, ZipArchive::CREATE);
	
	if( $R !== true ){
		die('<p>Zip fejlede!</p><a href="QRcreate.main.php" class="Button">Tilbage</a>');//DEBUG
		return false;
	} else if ($H=opendir($FolderPath)) {
		while( ($Item=readdir($H)) !== false ) {
			if( strpos($Item,$ImagePrefix) === 0 && substr($Item,-4) === '.png' ){
				$zip->addFile($FolderPath.$Item,$Item);
			}
		}
		closedir($H);
		$zip->close();
	}
	$Checksum = getChecksum($FolderPath);
	
	$FolderPath2 = substr($FolderPath,0,-1).$Checksum;
	rename($FolderPath,$FolderPath2);
	
	$ZipPath2 = substr($ZipPath,0,-4).$Checksum.'.zip';
	rename($ZipPath,$ZipPath2);
			
	return pathinfo($FolderPath2,PATHINFO_BASENAME);
}

?>
